import java.io.File;
import java.io.IOException;

/**
 * @author Sept Zhang
 * @create 2021-01-09 23:47
 */
public class GetFoldFileNames {
	public GetFoldFileNames(String path) throws IOException {
		File files = new File(path);
		File newFiles = new File(path+"/out");
		if(!newFiles.exists()){
			//如果文件夹不存在
			newFiles.mkdir();
			//创建文件夹
		}

		if(!files.exists()){
			System.out.println("文件路径错误");
			return;
		}
		File fileList[] = files.listFiles();
		for (File file:
		     fileList) {
			if (file.isDirectory()) {
				System.out.println("发现文件夹："+file.getName());
			}else {
				System.out.println("发现文件："+file.getName());
				System.out.println("更改名字："+toFormatName(file.getName()));
				file.renameTo(newFiles);

				File newName = new File(newFiles+"/"+toFormatName(file.getName()));
				if (newName.exists()) {
					//  确保新的文件名不存在
					throw new java.io.IOException("file exists");
				}
				if(file.renameTo(newName)) {
					System.out.println(newName.getName()+"已重命名");
				} else {
					System.out.println("Error");
				}
			}
			}
	}
	public String toFormatName(String fileName){
		char[] chars = fileName.toCharArray();
		String newName ="";
		//添加学号
		for (int i = 0; i < chars.length;i++){
			if (Character.isDigit(chars[i])){
			newName =newName+ String.valueOf(chars[i]);
			}
		}
		newName += "-";
		//添加姓名
		for (int i = 0; i < chars.length-2;i++){
			char c = chars[i];
			char ch = chars[i+1];
			if (c=='实' && ch=='验'){
				i =i + 2;
				continue;
			}else {
				if ((chars[i] >= 0x4e00)&&(chars[i] <= 0x9fbb)){
					newName += chars[i];
				}
			}
		}
		newName += "-";
		//添加实验x
		for (int i = 0; i < chars.length-1;i++){
			if (chars[i]=='实' && chars[i+1]=='验'){
				newName += "实验"+chars[i+2];
			}
		}

		//获取最后一个.的位置
		int lastIndexOf = fileName.lastIndexOf(".");
		//获取文件的后缀名 .jpg
		newName += fileName.substring(lastIndexOf);
		return newName;
	}
}
